import remoteSearchEmpInput from '../remote-search-emp-input';
import {
	quotationNuclearPriceRecordCreate,
	quotationNuclearPriceRecordGet, quotationNuclearPriceRecordUpdate,
	quotationNuclearPriceRecordUpdateAuditState
} from '../../../../../api/price/customerQuotation';
import handlerCache from '../../../../../mixins/handler-cache';
import remoteSearchBatchCodeInput from '../../../../production/qhPrd/productConfigCotton/components/remote-search-batch-code-input';
import { formatDate } from '../../../../../utils/jk/jk-tool';
import jkSaveButton from '../../../../jk-components/jk-save-button';
import { validateArr } from '../../../../../utils/jk/validator';
import dataTemplate from '../data-template';
import remoteSearchCustomerInput from '../../../../production/order/components/remote-search-customer-input';
import remoteSearchProductInput from '../../components/remote-search-product-input';
import surchargeOptionList from '../surcharge-option-list';
import coreOptionList from '../core-option-list';
import coarseSandOptionList from '../coarse-sand-option-list';
import { mathJsAdd, mathJsDiv, mathJsMul, mathJsSub } from '../../../../../utils/jk/jk-cals';
import totalFooter from '../total-footer';
let _this = null;
export default {
	components: {
		totalFooter,
		coarseSandOptionList,
		coreOptionList,
		surchargeOptionList,
		dataTemplate,
		remoteSearchProductInput,
		remoteSearchCustomerInput,
		jkSaveButton,
		remoteSearchEmpInput,
		remoteSearchBatchCodeInput
	},
	mixins: [handlerCache],
	props: {
		pageType: {
			type: String,
			default: 'add'
		}
	},
	data() {
		return {
			prefix: 'quotation:nuclearPriceRecord',
			dataId: null,
			apiItem: {
				'save': quotationNuclearPriceRecordCreate,
				'update': quotationNuclearPriceRecordUpdate
			},
			tableLoading: false,
			updateAuditLoading: false,
			auditStateLoading: false,
			saveBtnLoading: false,
			saveAndEnableBtnLoading: false,
			workshopList: [],
			showLoading: true,
			saveDialogState: false,
			cpRuleForm: {},
			ruleForm: {
				'belongDate': '',
				'subTotal': 0,
				'coarseSandItemList': [],
				'coreContent': null,
				'coreContentPrice': null,
				'coreContentAmount': null,
				'coreProductCode': '',
				'coreProductId': null,
				'coreProductModels': '',
				'coreProductName': '',
				'customerCode': '',
				'customerId': null,
				'customerName': '',
				'effectiveEndDate': '',
				'effectiveStartDate': '',
				'empCode': '',
				'empId': null,
				'empName': '',
				'surchargeAmount': null,
				'coarseSandCost': null,
				'coarseSandHc': null,
				'coarseSandHce': null,
				'coarseSandAmount': null,
				'offerPrice': null,
				'onePieceSilkItem': [],
				'processingFee': null,
				'productCode': '',
				'productId': null,
				'productModels': '',
				'productName': '',
				'profit': null,
				'spandexAmount': null,
				'spandexContent': null,
				'spandexPrice': null,
				'spandexNumber': null,
				'spandexProductCode': '',
				'spandexProductId': null,
				'spandexProductModels': '',
				'spandexProductName': '',
				'spandexQs': null,
				'surchargeItem': [],
				'yarnCount': null
			},
			rules: {
				coarseSandAmount: [{ required: true, trigger: 'change' }],
				coarseSandHce: [{ required: true, trigger: 'change' }],
				coarseSandHc: [{ required: true, trigger: 'change' }],
				coarseSandCost: [{ required: true, trigger: 'change' }],
				spandexNumber: [{ required: true, trigger: 'change' }],
				belongDate: [{ required: true, trigger: 'change' }],
				customerId: [{ required: true, trigger: 'change' }],
				dateRange: [{ required: true, validator: validateArr, trigger: 'change' }],
				offerPrice: [{ required: true, trigger: 'change' }],
				empId: [{ required: true, trigger: 'change' }],
				coreProductId: [{ required: true, trigger: 'change' }],
				coreContent: [{ required: true, trigger: 'change' }],
				coreContentPrice: [{ required: true, trigger: 'change' }],
				productId: [{ required: true, trigger: 'change' }],
				spandexProductId: [{ required: true, trigger: 'change' }],
				spandexQs: [{ required: true, trigger: 'change' }],
				spandexContent: [{ required: true, trigger: 'change' }],
				spandexAmount: [{ required: true, trigger: 'change' }],
				processingFee: [{ required: true, trigger: 'change' }],
				profit: [{ required: true, trigger: 'change' }],
				coreContentAmount: [{ required: true, trigger: 'change' }]
			},
			showTemplate: false,
			layoutConfig: {
				xl: { 'false': 6, 'true': 12 },
				lg: { 'false': 8, 'true': 12 },
				md: { 'false': 8, 'true': 12 },
				sm: { 'false': 12, 'true': 12 },
				xs: { 'false': 24, 'true': 24 }
			},
			isCopy: ''
		};
	},
	methods: {
		calAl() {
			if (this.ruleForm.spandexNumber && this.ruleForm.spandexQs) {
				// 氨纶丝含量 = 氨纶丝数据 / 9 / 牵伸 / 590.5 * 支数 * 1000
				let val = 0;
				val = mathJsDiv(this.ruleForm.spandexNumber || 0, 9);
				val = this.ruleForm.spandexQs ? mathJsDiv(val, this.ruleForm.spandexQs) : 0;
				val = mathJsDiv(val, 590.5);
				val = mathJsMul(val, this.ruleForm.yarnCount || 0);
				val = mathJsMul(val, 1000);
				val = Number(val.toFixed(1));
				this.$set(this.ruleForm, 'spandexContent', val);
				// 氨纶丝金额 = 氨纶丝含量 * 氨价
				this.$set(this.ruleForm, 'spandexAmount', mathJsMul(val, this.ruleForm.spandexPrice || 0));
			} else {
				this.$set(this.ruleForm, 'spandexContent', 0);
			}
		},
		calTotal() {
			let val = 0;
			val = mathJsAdd(val, this.ruleForm.coreContentAmount || 0);
			val = mathJsAdd(val, this.ruleForm.spandexAmount || 0);
			val = mathJsAdd(val, this.ruleForm.coarseSandAmount || 0);
			val = mathJsAdd(val, this.ruleForm.processingFee || 0);
			// 小计 = 一体丝金额 + 氨纶金额 + 粗纱金额 + 附加费用（基本加工费 + 其他项目费用，注：不含利润）
			this.ruleForm.surchargeItem.forEach(x => {
				val = mathJsAdd(x.price || 0, val);
			});
			this.$set(this.ruleForm, 'subTotal', val);
			// 报价 = 小计 + 利润
			this.$set(this.ruleForm, 'offerPrice', mathJsAdd(val, this.ruleForm.profit || 0));
		},
		onReturnDataOfCoarseSand(e) {
			this.$set(this.ruleForm, 'coarseSandItemList', e);
			this.calCs();
		},
		calCs() {
			// 	粗纱总价 = 所有粗纱原料总价之和
			let totalVal = 0;
			let itemVal = 0;
			if (this.ruleForm.coarseSandItemList && this.ruleForm.coarseSandItemList.length) {
				this.ruleForm.coarseSandItemList.forEach(x => {
					// 每个原料价格 = 百分比 * 损耗 * 单价 * 1000
					itemVal = mathJsMul(x.proportion / 100, x.loss);
					itemVal = mathJsMul(itemVal, x.price || 0);
					itemVal = mathJsMul(itemVal, 1000);
					itemVal = Number(itemVal.toFixed(1));
					x.rawMaterialPrice = itemVal;
					totalVal = mathJsAdd(totalVal, x.rawMaterialPrice || 0);
				});
			}
			this.$set(this.ruleForm, 'coarseSandCost', totalVal);
			// 	含粗 = 1000 - 一体丝含性芯 - 氨含
			let hcVal = mathJsSub(1000, this.ruleForm.coreContent || 0);
			hcVal = mathJsSub(hcVal, this.ruleForm.spandexContent || 0);
			hcVal = Number(hcVal.toFixed(1));
			this.$set(this.ruleForm, 'coarseSandHc', hcVal);
			// 	粗纱金额 = 粗纱总价 * 含粗
			// this.$set(this.ruleForm, 'coarseSandAmount', mathJsMul(totalVal, hcVal || 0));
			// 	含粗额 = 含粗 * 粗纱总价 / 1000
			let hceVal = 0;
			hceVal = mathJsMul(hcVal || 0, totalVal || 0);
			hceVal = mathJsDiv(hceVal, 1000);
			hceVal = Number(hceVal.toFixed(1));
			this.$set(this.ruleForm, 'coarseSandAmount', hceVal);
		},
		onReturnDataOfCore(e) {
			this.$set(this.ruleForm, 'onePieceSilkItem', e);
			this.calYts();
		},
		calYts() {
			// 芯含量 =（（一体丝数据1）/3+（一体丝数字2）+7）/ 9 / 590.5 * 支数 * 1000
			let val = 0;
			let item1 = 0;
			let item2 = 0;
			if (this.ruleForm.onePieceSilkItem.length === 2) {
				item1 = this.ruleForm.onePieceSilkItem[0].number || 0;
				item2 = this.ruleForm.onePieceSilkItem[1].number || 0;
				item1 = mathJsDiv(item1, 3);
				item2 = mathJsAdd(item2, 7);
				val = mathJsAdd(item1, item2);
				val = mathJsDiv(val, 9);
				val = mathJsDiv(val, 590.5);
				val = mathJsMul(val, this.ruleForm.yarnCount || 0);
				val = mathJsMul(val, 1000);
				val = val.toFixed(1);
				val = Number(val);
			}
			this.$set(this.ruleForm, 'coreContent', val);
			// 一体丝金额 = 含芯量 * 芯单价
			this.$set(this.ruleForm, 'coreContentAmount', mathJsMul(val, this.ruleForm.coreContentPrice || 0));
		},
		onReturnDataOfSurcharge(e) {
			this.$set(this.ruleForm, 'surchargeItem', e);
			this.calSurcharge();
		},
		calSurcharge() {
			// 附加费金额 = 基本加工费 + 其他项目费用总和
			let totalVal = 0;
			if (this.ruleForm.surchargeItem) {
				this.ruleForm.surchargeItem.forEach(x => {
					totalVal = mathJsAdd(x.price || 0, totalVal);
				});
			}
			totalVal = mathJsAdd(this.ruleForm.processingFee || 0, totalVal);
			this.$set(this.ruleForm, 'surchargeAmount', totalVal);
		},
		onSelectCustomerChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'customerId', e.id);
				this.$set(this.ruleForm, 'customerName', e.name);
			}
		},
		onEditBtn() {
			this.$toOtherRouter({
				name: 'editTechnology',
				query: {
					id: this.$route.query.id ? Number(this.$route.query.id) : null
				}
			});
		},
		async getDependentData() {
			this.showLoading = true;
			this.isCopy = this.$route.query.isCopy;
			this.showTemplate = false;
			this.dataId = this.$route.query.id ? Number(this.$route.query.id) : null;
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
			});
			// 新增页
			if (this.pageType === 'add') {
				this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
				this.$set(this.ruleForm, 'dateRange', [formatDate(Date.now()), formatDate(Date.now())]);
				this.$set(this.ruleForm, 'empId', this.$store.state.user.empInfo.id);
				this.$set(this.ruleForm, 'empName', this.$store.state.user.empInfo.name);
			}
			if (this.dataId) await this.getDetailRequest();
			this.showLoading = false;
		},
		onSelectEmpChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'empId', e.id);
				this.$set(this.ruleForm, 'empCode', e.code);
				this.$set(this.ruleForm, 'empName', e.name);
			}
		},
		onSelectProductChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'productId', e.productId);
				this.$set(this.ruleForm, 'productCode', e.productCode);
				this.$set(this.ruleForm, 'productName', e.productName);
				this.$set(this.ruleForm, 'productModels', e.productModels);
				this.$set(this.ruleForm, 'yarnCount', e.yarnCount);
				this.$set(this.ruleForm, 'processingFee', e.price);
			}
		},
		onSelectCoreProductChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'coreProductId', e.productId);
				this.$set(this.ruleForm, 'coreProductCode', e.productCode);
				this.$set(this.ruleForm, 'coreProductName', e.productName);
				this.$set(this.ruleForm, 'coreProductModels', e.productModels);
				this.$set(this.ruleForm, 'coreContentPrice', e.price);
			}
			this.calYts();
		},
		onSelectSpandexProductChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'spandexProductId', e.productId);
				this.$set(this.ruleForm, 'spandexProductCode', e.productCode);
				this.$set(this.ruleForm, 'spandexProductName', e.productName);
				this.$set(this.ruleForm, 'spandexProductModels', e.productModels);
				this.$set(this.ruleForm, 'spandexPrice', e.price);
			}
			this.calAl();
		},
		defaultRowData() {
			return {
				processId: null,
				processCode: '',
				processName: ''
			};
		},
		getParamData() {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			if (params.dateRange && params.dateRange.length) {
				params.effectiveStartDate = params.dateRange[0];
				params.effectiveEndDate = params.dateRange[1];
			}
			return params;
		},
		onConfirmBtn(type) {
			this.$refs['ruleForm'].validate(valid => {
				if (valid) {
					this.saveRequest(type);
				} else {
					this.$tipsBar(this, 'validator');
				}
			});
		},
		saveRequest(type) {
			if (type === 2) {
				this.saveAndEnableBtnLoading = true;
			} else {
				this.saveBtnLoading = true;
			}
			// 新增
			if (!this.dataId) {
				this.ruleForm.id = null;
				this.apiItem.save(this.getParamData()).then(res => {
					this.saveBtnLoading = false;
					this.saveAndEnableBtnLoading = false;
					if (res.data.status === 200) {
						this.dataId = res.data.res;
						if (type === 2) {
							this.enableRequest(this.dataId).then(res => {
								if (res.data.status === 200) {
									this.$tipsBar(this, 'save');
									this.onJump(this.dataId);
								}
							});
						} else {
							this.$tipsBar(this, 'save');
							this.onJump(res.data.res);
						}
					}
				});
				return;
			}
			// 编辑
			this.apiItem.update(this.getParamData()).then(res => {
				this.saveBtnLoading = false;
				this.saveAndEnableBtnLoading = false;
				if (res.data.status === 200) {
					if (type === 2) {
						this.enableRequest(this.dataId).then(res => {
							if (res.data.status === 200) {
								this.$tipsBar(this, 'save');
								this.getDependentData();
							}
						});
					} else {
						this.$tipsBar(this, 'save');
						this.getDependentData();
					}
				}
			});
		},
		onAuditStateChange() {
			this.auditStateLoading = true;
			this.enableRequest(this.dataId).then(res => {
				this.auditStateLoading = false;
				if (res.data.status === 200) {
					this.getDependentData();
				}
			});
		},
		enableRequest(id) {
			return quotationNuclearPriceRecordUpdateAuditState({ id });
		},
		onVisibleChange(e) {
			this.$emit('on-visible-change', e);
			if (!e) {
				Object.assign(this.$data, this.$options.data());
				this.$nextTick(() => {
					this.$refs.ruleForm.resetFields();
				});
			}
		},
		getDetailRequest() {
			return quotationNuclearPriceRecordGet({ id: this.dataId }).then(res => {
				this.showLoading = false;
				if (res.data.status === 200) {
					const resData = JSON.parse(JSON.stringify(res.data.res));
					delete resData.specSheetParamList;
					this.cpRuleForm = JSON.parse(JSON.stringify(resData));
					// 复制时，删除ID信息
					if (this.$route.query.isCopy === '1') {
						delete resData.id;
						resData.auditState = 0;
						this.dataId = null;
						resData.onePieceSilkItem.forEach(x => {
							delete x.id;
						});
						resData.coarseSandItemList.forEach(x => {
							delete x.id;
						});
						resData.surchargeItem.forEach(x => {
							delete x.id;
						});
					}
					this.ruleForm = resData;
					this.$set(this.ruleForm, 'dateRange', [this.ruleForm.effectiveStartDate, this.ruleForm.effectiveEndDate]);
				}
			});
		},
		onJump(id) {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toOtherRouter({
				name: 'editCustomerQuotation',
				query: { id }
			});
		},
		onJumpList() {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: 'CustomerQuotation'
			});
		},
		clearCacheMethod() {
			Object.assign(this.$data, this.$options.data());
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
				this.getDependentData();
			});
		}
	},
	mounted() {
		_this = this;
		this.getDependentData();
	},
	watch: {
		ruleForm: {
			handler() {
				this.calTotal();
			},
			deep: true
		}
	}
};
